<template>
  <forms ref="forms" :config="config" @submit:forms="onsubmit" :btns="btns">
  </forms>
</template>

<script>
import {ajax} from "@/js/api_tool.js";
import s94Mjs from "s94-js";
import {iframe} from "@/js/tool.js";
import {decode_config, s94_event} from "@/js/s94_tool.js";

export default {
  props: ['__iframe'],
  data(){
    let id = this.$get('id'), btns = undefined;
    let forms_config = {
      title: {name:'title', label:'任务标题', type:'text_one'},
      info: {name:'info', label:'任务详情', type:'text_more', tips:'任务介绍，简短阐述任务内容'},
      start_time: {name:'start_time', label:'开始时间', type:'date', tips:'任务开始时间，为空表示直接开始'},
      end_time: {name:'end_time', label:'结束时间', type:'date', tips:'任务结束时间，为空表示不会结束。'},
      user_frequency: {name:'user_frequency', label:'同一用户完成上限', type:'text_one', tips:'空字符表示无限制。格式：时间段(all,day,month,year):次数。例如：day:1 每天一次'},
      link_frequency: {name:'link_frequency', label:'同一项目完成上限', type:'text_one', tips:'空字符表示无限制。格式：时间段(all,day,month,year):次数。例如：day:1 每天一次'},
      user_link_frequency: {name:'user_link_frequency', label:'同一用户同一项目完成上限', type:'text_one', tips:'空字符表示无限制。格式：时间段(all,day,month,year):次数。例如：day:1 每天一次'},
      limit_score_level: {name:'limit_score_level', label:'段位限制', type:'checkbox', config:[], tips:'表示此任务仅对选定段位的用户有效和显示，为空表示不限制(所有用户)'},
      limit_level: {name:'limit_level', label:'等级限制', type:'checkbox', config:[], tips:'表示此任务仅对选定等级的用户有效和显示，为空表示不限制(所有用户)'},

      execute_id: {label:'完成后执行',name:'execute_id',type:'list_id',config:'/execute/index?model_name=user_task',tips:''},
      default_log_status: {name:'default_log_status', label:'需要审核', type:'radio_switch', config:'否|1,是|0', value:1, tips:'用户完成任务后，是否需要管理员后才执行奖励操作'},
      show: {name:'show', label:'显示位置', type:'checkbox', config:'用户积分|score', value:'', tips:''},
      judge_function: {label:'任务类型',name:'judge_function',type:'select_one',config:[],tips:''},
    }

    let function_map={}, field_map={};
    ajax({url:'/admin/user_task/config_map',cache:true,async:false},function (res){
      function_map = res.data.function_map;
      field_map = res.data.field_map;

      forms_config.judge_function.config = [];
      Object.keys(function_map).forEach((k)=>{
        forms_config.judge_function.config.push({content:function_map[k].content, value:k});
      })

      Object.keys(field_map).forEach((k)=>{
        forms_config[k] = field_map[k];
        forms_config[k].remove = true;
      })

      forms_config.limit_score_level.config = decode_config(res.data.score_level_list, {content_key:'title', value_key:'level'});
      forms_config.limit_level.config = decode_config(res.data.level_list, {content_key:'name', value_key:'level'});
      return false;
    })

    if (id){
      forms_config.create_time = {label:'创建时间',name:'create_time',tips:''};
    }
    if (this.$get('is_info')){
      s94Mjs.each(forms_config, function (row){ row.is_info = true; });
      btns = [];
    }
    return {
      id: id,
      btns: btns,
      config: forms_config,
      function_map: function_map,
      field_map: field_map,
    }
  },
  methods: {
    onsubmit(formData){
      let url = this.id ? `/admin/user_task/edit?id=`+this.id : '/admin/user_task/add';
      ajax({url:url, method:'POST', data:formData}, (res)=>{
        if (this.__iframe){
          s94_event(`user_task/${this.id?'edit':'add'}`, res);
          // iframe.exe('user_task/index', '$refs.list_url.list');
          iframe.hide('user_task/edit');
          if (!this.id) this.$refs['forms'].init();
        }else {
          this.$router.push('index');
        }
      }, (res)=>{
        if (res.errors) this.$refs['forms'].errors = res.errors;
      })
    },
    change_function(){
      let app = this;
      let func = this.config.judge_function.value;
      let params = !func || !app.function_map[func] ? [] : app.function_map[func].param;
      s94Mjs.each(app.field_map, function(v,k){
        if (~params.indexOf(k)){
          app.config[k].remove = false;
        }else {
          app.config[k].remove = true;
        }
      })
    },
  },
  watch:{
    'config.judge_function.value'(func){
      let app = this;
      this.change_function();
    },
  },
  mounted() {
    let app = this;
    if (!this.__iframe) window['app'] = this;
    if (this.id) {
      ajax({url:'/admin/user_task/info?id='+this.id, cache:true}, (res)=>{
        let param = JSON.parse(res.data.judge_param);
        delete res.data.param;
        app.$refs['forms'].init(res.data);
        setTimeout(function(){
          s94Mjs.each(app.field_map, function(row,k){
            if (app.config[k].remove) return;
            let ms = app.config[k].name.match(/param\[(\d+)\]/);
            if (ms && param[ms[1]]){
              app.config[k].value = param[ms[1]];
            }
          })
        },10)
        return false;
      }, ()=>{
        if (this.__iframe){
          iframe.remove('edit');
        }else {
          this.$router.push('user_task/index');
        }
      })
    }

    //其他初始化操作
  }
}
</script>
